package com.xm.xmds1705083.web.controller;

import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.BeanUtils;
import com.xm.xm.util.ErrorCode;
import com.xm.xm.util.HttpUtils;
import com.xm.xmds1705083.service.config.WxConfig;
import com.xm.xmds1705083.service.mapper.DuoduoWeixinUserMapper;
import com.xm.xmds1705083.service.model.DuoduoWeixinUser;
import com.xm.xmds1705083.service.service.WxService;
import com.xm.xmds1705083.service.util.XmlUtil;
import com.xm.xmds1705083.web.base.BaseController;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.util.calendar.BaseCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 杭州新苗网络科技有限公司
 *
 * @author meihf
 * @create 2017/6/26
 * @description
 */
@Controller
@RequestMapping("/weixin")
public class WxController extends BaseController{

    @Autowired
    WxService wxService;

    @RequestMapping("/auth")
    @ResponseBody
    public ResultDto auth(@RequestBody SearchDto searchDto){
        return wxService.auth(searchDto);
    }

    @RequestMapping("/getOpenId")
    //@ResponseBody
    public  String getOpenId(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @RequestParam(value = "code", required = true) String code,
                                  @RequestParam(value = "state", required = true) String state){
        logger.info("获取到的code"+code);
        WxConfig.CODE = code;
        WxConfig.STATE = state;
        String token_url = WxConfig.TOKEN_URL+"?appid="+WxConfig.APPID+"&secret="+WxConfig.APPSECRET+"&code="+WxConfig.CODE+"&grant_type=authorization_code";
        ResultDto result = BeanUtils.copy(HttpUtils.doGet(token_url,null),ResultDto.class);
        JSONObject result_json = JSONObject.fromObject(String.valueOf(result.getData()));
        String openid = result_json.getString("openid");
        logger.info("获取到的openid"+openid);
        String access_token = result_json.getString("access_token");
        String refresh_token = result_json.getString("refresh_token");
        String expires_in  = result_json.getString("expires_in");
        wxService.getUserInfo(openid,access_token,refresh_token,expires_in);
        return "redirect:"+WxConfig.REDIRECT_LOGIN_URL+"?openid="+openid;
    }

    @RequestMapping("/orderPay")
    @ResponseBody
    public ResultDto orderPay(@RequestBody SearchDto searchDto){
       /* searchDto.setAppUserId(getUserId());*/
        String authorization =   getRequest().getHeader("AUTHORIZATION");
        if (authorization!=null){
            searchDto.setAppUserId(Math.abs( Long.valueOf( authorization.split("\\_")[0] ) ));
        }
        searchDto.getFiled().put("ip",getIpAddr());
        return wxService.orderPay(searchDto);
    }

    /**
     * 微信回调方法
     *
     */
    @RequestMapping(value = "/weChatNotify", method = RequestMethod.POST)
    @ResponseBody
    public void notifyWx(HttpServletRequest request, HttpServletResponse response) throws Exception{

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = XmlUtil.parseXml(request.getInputStream());
        } catch (IOException e) {
            logger.error(String.valueOf(e.getCause()));
        }

        // 告诉微信服务器，我收到信息了，不要在调用回调
        ResultDto resultDto = wxService.weChatNotify(map);
        if (resultDto.getCode() == 0){
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/xml;charset=utf-8");
            response.setHeader("Cache-control", "no-cache");
            PrintWriter out = response.getWriter();
            out.write((String) resultDto.getData());
        }
    }

/*    @RequestMapping("/threadSock")
    @ResponseBody
    public ResultDto threadSock(HttpServletRequest request,HttpServletResponse response) {*/


}
